﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace LowLevelGraphics.Filter
{
    /// <summary>
    /// Laplace
    /// </summary>
    public class Laplace : BaseImageFilter
    {
        /// <summary>
        /// default constructor
        /// </summary>
        public Laplace()
        {
        }

        /// <summary>
        /// Used by clone to create a deep copy
        /// </summary>
        /// <param name="_laplace"></param>
        internal Laplace(Laplace _laplace)
        {
        }

        /// <summary>
        /// executes this filter
        /// </summary>
        /// <param name="_bitmap"></param>
        public override UnsafeBitmap Execute(UnsafeBitmap _bitmap)
        {
            UnsafeBitmap bitmap = _bitmap;

            int nWidth = bitmap.Width;
            int nHeight = bitmap.Height;

            int r = 0;
            int g = 0;
            int b = 0;

            Color c = Color.Transparent;

            int y = 0;
            int x = 0;

            for (y = 1; y < nHeight - 1; y++)
            {
                for (x = 1; x < nWidth - 1; x++)
                {
                    Color c00 = bitmap.GetPixel(x - 1, y - 1);
                    Color c01 = bitmap.GetPixel(x - 1, y);
                    Color c02 = bitmap.GetPixel(x - 1, y + 1);
                    Color c10 = bitmap.GetPixel(x, y - 1);
                    Color c11 = bitmap.GetPixel(x, y);
                    Color c12 = bitmap.GetPixel(x, y + 1);
                    Color c20 = bitmap.GetPixel(x + 1, y - 1);
                    Color c21 = bitmap.GetPixel(x + 1, y);
                    Color c22 = bitmap.GetPixel(x + 1, y + 1);
                    r = -c00.R - c01.R - c02.R +
                            -c10.R + 8 * c11.R - c12.R +
                            -c20.R - c21.R - c22.R;
                    g = -c00.G - c01.G - c02.G +
                            -c10.G + 8 * c11.G - c12.G +
                            -c20.G - c21.G - c22.G;
                    b = -c00.B - c01.B - c02.B +
                            -c10.B + 8 * c11.B - c12.B +
                            -c20.B - c21.B - c22.B;
                    r = Math.Min(255, Math.Max(0, r));
                    g = Math.Min(255, Math.Max(0, g));
                    b = Math.Min(255, Math.Max(0, b));
                    c = Color.FromArgb(r, g, b);
                    bitmap.SetPixel(x, y, c);
                }
            }
            return bitmap;
        }

        /// <summary>
        /// create a deep copy
        /// </summary>
        /// <returns></returns>
        public override object Clone()
        {
            return new Laplace(this);
        }
    }
}
